package com.gwd.task.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.gwd.task.entity.TaskProcessEntity;
import com.gwd.task.model.TaskProcessDTO;
import com.gwd.task.model.UserDTO;
import com.gwd.task.repository.TaskProcessRepository;
import com.gwd.task.services.TaskProcessServer;
import com.gwd.task.services.UserServer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/11/26 18:14
 */
@Service
public class TaskProcessServerImpl implements TaskProcessServer{

    @Resource
    private TaskProcessRepository taskProcessRepository;
    @Resource
    private UserServer userServer;

    @Override
    public List<TaskProcessDTO> findAll() {
        return taskProcessRepository.findAll().stream().map(TaskProcessDTO::new).collect(Collectors.toList());
    }

    @Override
    public List<TaskProcessDTO> findByTaskId(Long id) {
        List<TaskProcessDTO> list =  taskProcessRepository.findByTaskId(id).stream().map(TaskProcessDTO::new).collect(Collectors.toList());
        List<UserDTO> users = userServer.findAll();
        list.forEach(process -> users.forEach(user -> {
            if (user.getUserId().equals(process.getOperationUser())) {
                process.setOperationUserName(user.getUserName());
            }
        }));
        return list;
    }

    @Override
    public List<TaskProcessDTO> findByTaskIdList(List<Long> idList) {
        List<TaskProcessDTO> list = taskProcessRepository.findByTaskIdIn(idList).stream().map(TaskProcessDTO::new).collect(Collectors.toList());
        List<UserDTO> users = userServer.findAll();
        list.forEach(process -> users.forEach(user -> {
            if (user.getUserId().equals(process.getOperationUser())) {
                process.setOperationUserName(user.getUserName());
            }
        }));
        return list;
    }

    @Override
    public void save(TaskProcessDTO dto) {
        TaskProcessEntity entity = new TaskProcessEntity();
        BeanUtil.copyProperties(dto, entity, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        taskProcessRepository.save(entity);
    }
}
